package com.zrf.base.knowledge.concurrent.demo;

import org.apache.commons.lang3.RandomUtils;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @date 2020/3/24
 * @AUTHER zhouruifeng
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();

                    System.out.println(Thread.currentThread().getName() + " enter");
                    TimeUnit.SECONDS.sleep(RandomUtils.nextInt(0,3));
                    System.out.println(Thread.currentThread().getName() + " exit");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    semaphore.release();
                }
            }).start();
        }
    }
}
